﻿using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HimVoiceStudio.Audio
{
    public class DisposableWaveToSampleProvider : ISampleProvider,IDisposable
    {

        IWaveProvider _waveProvider;
        ISampleProvider _sampleProvider;
        public DisposableWaveToSampleProvider(IWaveProvider waveProvider)
        {
            _waveProvider = waveProvider;
            _sampleProvider = waveProvider.ToSampleProvider().ToMono();
            if(_sampleProvider.WaveFormat.SampleRate != 44100)
            {
                _sampleProvider = new WdlResamplingSampleProvider(_sampleProvider, 44100);
            }
        }


        public WaveFormat WaveFormat => _sampleProvider.WaveFormat;

        public void Dispose()
        {
            if(_waveProvider is IDisposable d)
            {
                d?.Dispose();
            }
        }

        public int Read(float[] buffer, int offset, int count)
        {
            return _sampleProvider.Read(buffer, offset, count);
        }


        public DisposableWaveToSampleProvider Splice(float start,float end)
        {
            _sampleProvider = _sampleProvider.Skip(TimeSpan.FromSeconds(start)).Take(TimeSpan.FromSeconds(end - start));
            return this;
        }
    }
}
